<template slot-scope="scope">
    <el-container class="main_box">
      <el-aside width="250px">
         <div class="main_le_icon">
          <img src="../public/logo.png" />
         </div>
         <div class="main_le_list">
          <div class="main_le_title">
            工作区
          </div>
          <div class="main_le_list_items">
            <ul class="main_le_list_items_ul">
              <li class="main_le_list_items_li" 
              v-for="(id, pos) in workList"
              :key="i"
              @click="setCurSelPos(pos, id)">
                <WorkListItem
                :dataObj="searchContent[getPos(id)]||{}"
                :selFlag="pos == curSelPos"
                />
              </li>
            </ul>
          </div>
         </div>
      </el-aside>

      <el-container class="main_ri">
        <el-header>
          <el-row>
            <el-col :span="20" class="btns_out_box">
              <div class="btns">
                <el-button key="search"  type="primary" text
                @click="toMainPage">
                  <svg-icon name="all"
                      :size="20"
                      :margin="5"
                      color="blue"/>
                  探索
                </el-button>
                <el-button key="search"  type="primary" text>
                  <svg-icon name="db"
                      :size="20"
                      :margin="5"
                      color="blue"/>
                  数据库
                </el-button>
                <el-button key="search"  type="primary" text>
                  <svg-icon name="t"
                      :size="20"
                      :margin="5"
                      color="blue"/>
                  AIT-数藏阁
                </el-button>
              </div>
            </el-col>

            <el-col :span="4">
              <div class="species">
                <div class="main_img_species">
                  <el-popover
                    placement="top-start"
                    :width="200"
                    trigger="hover">
                   <div class="top_box">
                    <ul>
                      <li >
                        <svg-icon name="priceicon"
                        :size="35"
                        :margin="5"
                        color="blue"/>
                        <span>
                          {{ curUser.name }}
                        </span>
                      </li>
                      <li class="pink_box">
                        <el-row :gutter="15"
                        >
                          <el-col :span="14">
                            <div class="il_le clearfix"
                              >
                              <div class="il_le_le fl">
                                积分
                              </div>
                              <div class="il_le_ri fr"
                              style="">
                                <el-text class="mx-1" type="danger">
                                  {{ curUser.score }}
                                </el-text>
                              </div>
                            </div>
                          </el-col>

                          <el-col :span="10">
                            <div class="il_ri">
                              <el-link type="danger">
                                充值 
                              </el-link>
                              <svg-icon name="rightarrow"
                                  :size="13"
                                  :margin="5"/>
                            </div>
                          </el-col>
                        </el-row>
                      </li>
                      <li>
                        <el-button class="bo_btn">
                          退出登录
                        </el-button>
                      </li>
                    </ul>
                   </div>

                    <template #reference>
                      <div class="box">
                        <svg-icon name="priceicon"
                        :size="35"
                        :margin="5"
                        color="blue"/>
                        <span>
                          <!-- {{ money }} -->
                          {{ curUser.name ? curUser.name : 'name' }}
                        </span>
                      </div>
                     
                    </template>
                  </el-popover>

                </div>
              </div>
            </el-col>

          </el-row>
        </el-header>
        
        <el-main width="1000px">
          <router-view></router-view>
        </el-main>

        <el-footer>
          <el-link type="info">
            Copyright © 2023 Tools-AI. All rights reserved.
          </el-link>
        </el-footer>
      </el-container>

    </el-container>

    <el-dialog
      v-model="data.loginDialogVisible"
      title="登录"
      width="30%" >
      <template #footer>
        <span class="dialog-footer">
          <div class="dailog_username_div">
            <el-input class="dailog_username" 
              v-model="data.user.username"
              type="text"
              placeholder="请输入用户名"
              clearable
              autofocus
            />
            <!-- @input="updatePassword" -->
            <el-input
              
              class="dailog_password" 
                v-model="data.user.password"
                type="password"
                placeholder="请输入密码"
                show-password
                clearable
                @keydown.enter="loginMethod"
              />
          </div>

          <div class="dailog_password_div">
            
          </div>
          <el-button @click="data.loginDialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="loginMethod">
            登录
          </el-button>
        </span>
      </template>
    </el-dialog>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import {reqLogin, getModelList, reqReLogin, getModelDetail} from './api/index.js'
import { ref, computed, onMounted } from 'vue';
import { useStore } from 'vuex';
import { useRouter, useRoute } from 'vue-router'
import WorkListItem from './components/workListItem.vue'

const router = useRouter()
const route = useRoute()
const store = useStore()

const curUser = computed(() => store.state.curUser)
const workList = computed(() => store.state.workList)
const searchContent = computed(() => {
  return store.state.searchContent
})
const curSelPos = computed(()=> store.state.curSelPos);
const getPos = (id) => {
  let search = searchContent.value;
  for (let i = 0; i < search.length; i++) {
    if (search[i].id == id) return i;
  }
  return 0;
}
onMounted(() => {
// localStorage.removeItem('token')
  let tToken = localStorage.getItem('token')
  console.log('token=', tToken);
  store.dispatch('setToken', tToken);
  // token不为空
  if(tToken) {
    let res = reqReLogin(tToken);
    res.then((resData) => {
      if (resData.data.code == 200) {
        // 隐藏登录弹框
        data.value.loginDialogVisible = false;
        let resp_data = resData.data.resp_data;
        resp_data.token = tToken;
        setCurUserInfo(resp_data)
        // 去拿search模块
        getSearchModel(tToken);
        let worlL = JSON.parse(localStorage.getItem('worklist'));
        if (worlL != undefined && worlL != null && worlL.length > 0) {
          store.dispatch('setWorkList', worlL);
        }
      }
    }).catch((err) => {
      console.log(err);
    })
  }else {
    console.log('没有缓存token');
  }
});

const data = ref({
  loginDialogVisible: true,
  user: {// 存放用户信息
    username: '',
    password: '',
    token:''
  },
});

const setCurUserInfo = (data) => {
  store.dispatch('setCurUserInfo', data)
}
const addSearchContent = (arr) => {
  // console.log('arr', arr);
  store.dispatch('addSearchContent', arr) 
}

const setCurSelPos= (pos, id) => { 
  // 请求detail
  let res = getModelDetail(curUser.value.token, id)
  res.then((dataP) => {
    if (dataP.data.code == 200) {
      store.dispatch('setSearchItem', {data:dataP.data.resp_data, id: id})
      store.dispatch('setCurSelPos', pos)
      console.log('拿到detail', dataP.data.resp_data);
        // 内容详情显示
      let path = '';
      if (dataP.data.resp_data.type == 1) {
        path = '/Search/ArticleRepeatItem';
      }else {
        path = '/Search/item';
      }
      router.push({
        path,
        query: {
          id
        }
      })
    }
  }).catch(e=> {
    console.log(e);
    ElMessage.error('网络错误');
  })
}

const loginMethod = () => {
  let {username, password} = data.value.user;
  console.log('username=' + username + ", password=" +password);
  if (!username || username == '' || !password || password == '' ) {
    ElMessage.error('密码或用户名不能为空! !!');
    return;
  }
  let res = reqLogin({name:username, passwd:password})

  res.then((dataP) => {
    let innerSdata = dataP.data;
    let {resp_data} = innerSdata

    if (innerSdata.code == 200) {
      //登录成功
      ElMessage({
        message: '登录成功.',
        type: 'success',
      })
      // 保存信息
      store.dispatch('setToken', resp_data.token)
      localStorage.setItem('token', resp_data.token)
      setCurUserInfo(resp_data)
      // 去拿search模块
      getSearchModel(resp_data.token);
    }else {
      ElMessage.error(resp_data.code_msg)
    }
    // console.log(data);
    return;
  }).catch(err => {
    // 登陆失败
    ElMessage.error('登录失败.')
    console.log(err);
    return;
  });
  clearLoginFormData();
}
   // 拿所有模块
const  getSearchModel = (token) => {
     let res = getModelList(token);
     console.log('res 306', res);
    res.then((tData) => {
      let innerData = tData.data;
      console.log("data", innerData);
      if (innerData.code == 200) {
        console.log(innerData.resp_data);
        addSearchContent(innerData.resp_data.module_list)
        // workList.push.apply(workList, innerData.resp_data.module_list);
        // 拿到数据隐藏弹窗
        data.value.loginDialogVisible = false;
        console.log('**', searchContent.value);
        // console.log('拿到数据隐藏弹窗', searchContent, data.value.loginDialogVisible);
      }else {
        ElMessage.error(innerData.code_msg)
      }
    }).catch(err => {
      ElMessage.error("请求错误", err)
    })
    clearLoginFormData();
}
  // 清除弹窗表单数据
const clearLoginFormData = () => {
  data.value.user.username = '';
  data.value.user.password = '';
}

const toMainPage = () => {
  router.push({path:'/'})
}
</script>

<style scoped>
.main_box {
  height: 788px;
}
.main_le_icon{
  height: 90px;
}
.main_le_title {
  line-height: 60px;
  margin-left: 13px;
}
.el-header {
  height: 60px;
  line-height: 60px;
  width: 1250px;
}
.el_header .el_button {
  text-align: center;
}
.btns_out_box{
  position: relative;
}
.btns {
  position: absolute;
  left: 50%;
  transform: translate(-50%, 0);
}
.main_ri {
  width: 1250px;
  height: 100%;
}
.el-main {
  width: 100%;
  height: 100%;
}
.dailog_username, .dailog_password {
  margin: 20px;
  width: 90%;
}
.dailog_password {

}
.dailog_password_div{
  margin-top: 20px;
}

.top_box ul li{
  list-style: none;
}

.pink_box {
  background-color: #f9d2d2;
  border-radius: 10px;
  line-height: 20px;
  height: 20px;
  padding: 10px;
}

.bo_btn {
  width: 100%;
  margin-top: 10px;
}
</style>
